package cn.itcast.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.common.GoodsDTO;
import cn.itcast.config.VisibleThreadPoolTaskExecutor;
import cn.itcast.controller.entity.GoodsEntity;
import cn.itcast.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
@RestController
@Slf4j
public class RlController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> mailList=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    public static Integer currentId=0;
    @Autowired
    private VisibleThreadPoolTaskExecutor executor;
    @RequestMapping("/createMarket")
    public String createMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(list)){
            try{
                IpBean ipBean1 = new IpBean();
                ipBean1.setIpAddress("117.160.250.132");
                ipBean1.setPort(8080);
                list.add(ipBean1);
            }catch (Exception e){
                IpBean ipBean=new IpBean();
                list.add(ipBean);
            }
        }
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int j=0;j<list.size();j++){
                    for(int z=0;z<tokenList.size();z++){
                        IpBean ipBean=list.get(j);
                        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipBean.getIpAddress(), ipBean.getPort()));
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1000);
                    }

                }
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####热浪执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####创建订单失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        JSONObject requestJson = new JSONObject();
        requestJson.putOnce("goods_id", goodsId);
        requestJson.putOnce("page", 1);
        requestJson.putOnce("page_size", "100");
        requestJson.putOnce("sort_type", 2);
        JSONObject response=null;
        String result=null;
        try{
            result = HttpRequest.post("https://www.srelang.cn/h5/super/api/member/getDetailsSealList")
                    .body(requestJson.toString())
                    .header("token",token)
                    .execute().body();
            response= JSONUtil.parseObj(result);
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(null!=response && response.get("code").toString().equals("1")){
            JSONObject jsonData=JSONUtil.parseObj(response.get("data").toString());
            JSONArray jsonArray=JSONUtil.parseArray(jsonData.get("data").toString());
            List<GoodsEntity> goodsList= JSONUtil.toList(jsonArray,GoodsEntity.class);
            if(!CollectionUtils.isEmpty(goodsList)){
              for(GoodsEntity goodsEntity:goodsList){
                  if(goodsEntity.getSalePrice().compareTo(new BigDecimal(salePrice))<=0){
                      Proxy finalProxy = null;
                      executor.execute(()->{
                          saveOrder(finalProxy,token,goodsEntity.getId(),goodsId);
                      });
                      Thread.sleep(1000);
                  }
              }
            }
        }
    }
    public void saveOrder(Proxy proxy,String token,String id,String goodsId){
        JSONObject createJson = new JSONObject();
        createJson.putOnce("goods_id", goodsId);
        createJson.putOnce("order_type", 3);
        createJson.putOnce("id", id);
        String createResult = HttpRequest.post("https://www.srelang.cn/h5/super/order/createOrder").
                body(createJson.toString())
                .header("token",token)
                .execute().body();
        log.info("####支付结果######"+createResult);
        JSONObject createResponse= JSONUtil.parseObj(createResult);
        Integer code=createResponse.get("code",Integer.class);
        if(1==code ){
            //请求数据生成url连接
            log.error("####生成订单数据######"+createResult);
            MailUtil.send("1027060531@qq.com", "收到订单", "您有一个订单，请赶紧支付！", false);
        }
    }
    public void addToken(){
        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9zdXBlclwvIiwiYXVkIjoiaHR0cDpcL1wvc3VwZXJcLyIsImlhdCI6MTcxNDAzMzYwMiwibmJmIjoxNzE0MDMzNjAyLCJleHAiOjE3MTQxMjAwMDIsIm1lbWJlcl9pbmZvIjo0Nzc3N30.cE-__mAJeCyikW51FT82-Yfy0qsMOhG6G-arBv3mfOA");
    }
    public void addMail(){
        mailList.add("1027060531@qq.com");
    }
    @RequestMapping("/creteTiele")
    public String creteTiele(@RequestParam(value = "num",defaultValue = "10000") Integer num,@RequestParam(value = "id",defaultValue = "1")Integer id) {
        if(CollectionUtils.isEmpty(tokenList)){
            addMail();
        }
        for(int i=0;i<num;i++){
            try {
                String createResult = HttpRequest.get("https://www.srelang.cn/h5/super/member/notice2")
                        .execute().body();
                JSONObject createResponse= JSONUtil.parseObj(createResult);
                JSONArray jsonArray=JSONUtil.parseArray(createResponse.get("data").toString());
                JSONObject object= (JSONObject) jsonArray.get(0);
                GoodsDTO goodsDTO=JSONUtil.toBean(object.toString(),GoodsDTO.class);
                if(currentId ==0){
                    currentId=goodsDTO.getId();
                }
                if(goodsDTO.getId()>currentId){
                      currentId=goodsDTO.getId();
                      for(int z=0;z<mailList.size();z++){
                          MailUtil.send(mailList.get(z), goodsDTO.getTitle(), goodsDTO.getContent(), true);
                      }
                  }
                Thread.sleep(5000);
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }

        }
        log.info("####热浪执行完成#####");
        return null;
    }

}
